package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final WeChatProperties weChatProperties;

    private final JwtProperties jwtProperties;

    private final String jscode2session_url = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserLoginVO login(String code) {
        JSONObject jsonObject = getOpenIdByCode(code);
        String openid = jsonObject.getString("openid");
        if (Objects.isNull(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2.校验重复性
        User user = userMapper.selectByOpenId(openid);
        if (Objects.isNull(user)){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            //主键返回
            userMapper.insert(user);
        }

        //3.实现结果的封装和返回
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);

        //创建JWT
        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(), map);
        userLoginVO.setToken(token);

        return userLoginVO;
    }

    private JSONObject getOpenIdByCode(String code) {
        HashMap<String,String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", code);
        param.put("grant_type","authorization_code");
        String reponseJson = HttpClientUtil.doGet(jscode2session_url, param);
        log.info("校验后的结果:{}",reponseJson);

        JSONObject jsonObject = JSON.parseObject(reponseJson);
        return jsonObject;
    }
}
